<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>

      </div>

      <!-- 放置table组件 -->
      <el-table :data="roleList">
        <!-- 放置列 -->
        <el-table-column prop="id" align="center" width="80" label="序号" />
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template v-slot="{ row }">
            <!-- 条件判断 -->
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <template v-slot="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>{{ row.state === 1? '已启用' : row.state === 0? '未启用' : '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template v-slot="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{ row }">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="updateRole(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>

            <template v-else>
              <el-button size="mini" type="text" @click="btnAssignPerm(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row)">编辑</el-button>
              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>

          </template>
        </el-table-column>
      </el-table>

      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          layout="prev, pager, next"
          @current-change="changePage"
        />
      </el-row>

    </div>

    <!-- 弹层组件 -->
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="btnCancel">
      <!-- 表单内容 -->
      <el-form ref="form" label-width="120px" :model="form" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" style="width:300px" size="mini" />
        </el-form-item>

        <el-form-item label="启用">
          <el-switch v-model="form.state" size="mini" :active-value="1" :inactive-value="0" />
        </el-form-item>

        <el-form-item label="角色描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" style="width:300px" size="mini" />
        </el-form-item>

        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="btnOk">确定</el-button>

              <el-button size="mini" @click="btnCancel">取消</el-button>

            </el-col>

          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog :visible.sync="showPermissionDialog" title="分配权限" width="500px">
      <el-tree
        ref="premTree"
        node-key="id"
        :default-checked-keys="permIds"
        show-checkbox
        default-expand-all
        :data="permissionList"
        :props="defaultProps"
        check-strictly="true"
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="8">
          <el-button type="primary" size="mini" @click="btnPermissionOk">确定</el-button>

          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>

        </el-col>

      </el-row>
    </el-dialog>
  </div>

</template>
<script>
import { getPermissionList } from '@/api/permission'
import { addRole, assignPrem, delRole, getRoleDetail, getRoleList, updateRole } from '@/api/role'
import { transListToTreeData } from '@/utils'

export default {
  name: 'RoleIndex',
  data() {
    return {
      currentRoleId: null,
      permissionList: [],
      permIds: [],
      showPermissionDialog: false,
      defaultProps: { label: 'name', children: 'children' },
      roleList: [],
      pageParams: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      showDialog: false,
      // 角色表单
      form: {
        name: '',
        description: '',
        state: 0
      },
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 修改权限
    async btnPermissionOk() {
      await assignPrem({
        id: this.currentRoleId,
        permIds: this.$refs.premTree.getCheckedKeys()
      })
      this.$message.success('分配权限成功')
      this.showPermissionDialog = false
    },
    // 分配权限
    async btnAssignPerm(id) {
      this.currentRoleId = id
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.permissionList = transListToTreeData(await getPermissionList(), 0)
      // 弹出框
      this.showPermissionDialog = true
    },
    // 点击编辑行
    btnEditRow(row) {
      row.isEdit = true // 改变行的编辑状 态
      // 更新缓存状态  输入框/文本域的值与默认保持一致
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    // 获取角色列表
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      console.log('res', rows)
      this.roleList = rows
      // 数据总数
      this.pageParams.total = total
      // 针对每一行数据添加一个编辑标记
      this.roleList.forEach(item => {
        // item.isEdit = false // 添加一个属性 初始值为false
        // 数据响应式的问题  数据变化 视图更新
        // 添加的动态属性 不具备响应式特点
        // this.$set(目标对象, 属性名称, 初始值) 可以针对目标对象 添加的属性 添加响应式
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    // 分页
    changePage(newPage) {
      this.pageParams.page = newPage
      this.getRoleList()
    },
    // 弹层表单提交
    async btnOk() {
      this.$refs.form.validate()
      await addRole(this.form)
      this.$message.success('新增角色成功')
      this.getRoleList()
      this.btnCancel()
    },
    // 弹层表单取消
    btnCancel() {
      this.showDialog = false
      this.$refs.form.resetFields()
    },
    async updateRole(row) {
      if (row.editRow.name && row.editRow.description) {
        await updateRole({ ...row.editRow, id: row.id })
        this.$message.success('更新角色成功')
        //eslint 误判
        // 1.手动消除误判提示
        // eslint-disable-next-line require-atomic-updates
        // row.isEdit = false
        // eslint-disable-next-line require-atomic-updates
        // row.name = row.editRow.name
        // 2.object.assign(target, source)
        Object.assign(row, {
          ...row.editRow,
          isEdit: false // 退出编辑模式
        })
      } else {
        this.$message.error('角色名称和描述不能为空')
      }
    },
    async confirmDel(id) {
      await delRole(id) // 后端删除
      this.$message.success('删除角色成功')
      // 删除的如果是最后一个
      if (this.roleList.length === 1) this.pageParams.page--
      this.getRoleList()
    }
  }
}

</script>
<style lang="scss" scoped>
.role-operate {
  padding: 10px;
}
</style>
